<template>
  <el-card>
    <!--    卡片按钮-->
    <el-button type="primary" size="default" icon="plus" @click="addTrademark">
      添加品牌
    </el-button>

    <el-table :data="tableData" border style="width: 100%; margin: 10px 0">
      <el-table-column
        label="序号"
        type="index"
        prop="date"
        width="80"
        align="center"
      />
      <el-table-column label="品牌名称" prop="tmName" width="180" />
      <el-table-column label="品牌Logo" prop="logoUrl">
        <template #default="{ row }">
          <el-image
            :src="row.logoUrl"
            alt="图片缺失"
            style="width: 100px; height: 100px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="edit"
            @click="updateTrademark(row)"
          >
            修改
          </el-button>
          <el-popconfirm
            :title="`确定删除 ${row.tmName} 吗？`"
            cancel-button-text="取消"
            confirm-button-text="确定"
            @confirm="deleteTrademark(row)"
            width="200"
            icon="delete"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper, ->,sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="addOrUpdateDialog"
      :title="trademarkForm.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form :model="trademarkForm" :rules="rules" ref="trademarkFormRef">
        <el-form-item label="品牌名称" :label-width="100" prop="tmName">
          <el-input
            v-model="trademarkForm.tmName"
            autocomplete="off"
            placeholder="请输入品牌名称"
          />
        </el-form-item>
        <el-form-item label="品牌Logo" :label-width="100" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${VITE_APP_BASE_API}/admin/product/fileUpload`"
            :show-file-list="false"
            :headers="uploadHeaders"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
          >
            <img
              v-if="trademarkForm.logoUrl"
              :src="trademarkForm.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm(trademarkFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts" name="index">
import {
  reqTrademarkList,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type { Trademark } from '@/api/product/trademark/type.ts'
import { computed, onMounted, reactive, ref, nextTick } from 'vue'
import useUserStore from '@/store/modules/user.ts'
import { ElMessage, type FormInstance, type UploadProps } from 'element-plus'

const userStore = useUserStore()
const VITE_APP_BASE_API = import.meta.env.VITE_APP_BASE_API
onMounted(() => {
  getTrademarkList()
})
let tableData = ref<Trademark[]>([])
//当前页码
let currentPage = ref<number>(1)
//每页显示多少条
let pageSize = ref<number>(3)
let size = ref('small')
let disabled = ref(false)
let background = ref(true)
//总数
let total = ref<number>(100)
function handleSizeChange(val: number) {
  console.log(`每页 ${val} 条`)
  console.log('pageSize', pageSize)
  getTrademarkList()
}
function handleCurrentChange(val: number) {
  console.log(`当前页: ${val}`)
  getTrademarkList(currentPage.value)
}

const getTrademarkList = async (page: number = 1) => {
  currentPage.value = page
  const result = await reqTrademarkList(currentPage.value, pageSize.value)
  if (result.code == 200) {
    total.value = result.data.total
    tableData.value = result.data.records
  }
}
const uploadHeaders = computed(() => ({
  Token: userStore.token,
}))
//控制对话框的显示与隐藏
let addOrUpdateDialog = ref(false)
//获取表单ref
let trademarkFormRef = ref()
//表单数据
let trademarkForm = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})
//品牌LogoUrl自定义校验
const validateLogoUrl = (_rule: any, value: string) => {
  if (!value) {
    return new Error('请上传品牌Logo')
  }
  return true
}
const rules = {
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  logoUrl: [{ required: true, validator: validateLogoUrl }],
}
//添加品牌
const addTrademark = () => {
  addOrUpdateDialog.value = true
  resetForm()
  //第一种写法 ?.
  // trademarkFormRef.value?.clearValidate('tmName')
  // trademarkFormRef.value?.clearValidate('logoUrl')
  //第二种写法
  nextTick(() => {
    trademarkFormRef.value.clearValidate('tmName')
    trademarkFormRef.value.clearValidate('logoUrl')
  })
}
//修改品牌
const updateTrademark = (row: Trademark) => {
  console.log('updateTrademark===>', row)
  addOrUpdateDialog.value = true
  Object.assign(trademarkForm, row)
  //清空校验错误提示信息
  trademarkFormRef.value?.clearValidate('tmName')
  trademarkFormRef.value?.clearValidate('logoUrl')
}
//删除品牌
const deleteTrademark = async (row: Trademark) => {
  let res = await reqDeleteTrademark(row.id as number)
  if (res.code == 200) {
    ElMessage.success('删除品牌成功')
    //删除品牌成功后 刷新当前页数据
    if (tableData.value.length < 1) {
      currentPage.value = currentPage.value === 1 ? 1 : currentPage.value - 1
    }
    getTrademarkList(currentPage.value)
  } else {
    ElMessage.error('删除品牌失败')
  }
}
//取消
const cancel = () => {
  addOrUpdateDialog.value = false
}

const resetForm = () => {
  Object.assign(trademarkForm, {
    tmName: '',
    logoUrl: '',
    id: null,
  })
}
//确定
const confirm = async (formEl: FormInstance | undefined) => {
  //校验表单项
  if (!formEl) return
  formEl.validate(async (valid, _invalidFields) => {
    if (valid) {
      let res = await reqAddOrUpdateTrademark(trademarkForm)
      console.log('res', res)
      if (res.code == 200) {
        ElMessage.success(trademarkForm.id ? '修改品牌成功' : '添加品牌成功')
        addOrUpdateDialog.value = false
        getTrademarkList(trademarkForm.id ? currentPage.value : 1)
      } else {
        ElMessage.error(trademarkForm.id ? '修改品牌失败' : '添加品牌失败')
      }
    }
    /*else {
      // 汇总所有错误信息
      const errorMessages = Object.values(invalidFields)
        .flat()
        .map((field) => field.message)
      const errorMessage = errorMessages.join('；') // 用中文分号拼接
      ElMessage.error(errorMessage)
    }*/
  })
}
//上传图片之前 约束 文件类型 大小
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //格式为：png\jpg\gif
  if (
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('品牌图片格式只能是png，jpg，gif格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error('图片不能大于 3MB!')
    return false
  }
  return true
}
const handleUploadSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  console.log('response==>', response)
  console.log('uploadFile==>', uploadFile)

  trademarkForm.logoUrl = response.data
  //图片上传成功，清除表单校验错误提示信息
  trademarkFormRef.value?.clearValidate('logoUrl')
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
